#include <stdio.h>
#include "nopoll.h"

void listener_on_message (noPollCtx * ctx, noPollConn * conn, noPollMsg * msg, noPollPtr  user_data) {
        // print the message (for debugging purposes) and reply
        printf ("Listener received (size: %d, ctx refs: %d): (first %d bytes, fragment: %d) '0x%s '\n", 
                nopoll_msg_get_payload_size (msg),
                nopoll_ctx_ref_count (ctx), 1, nopoll_msg_is_fragment (msg), nopoll_msg_get_payload(msg));
    	//printf("userdata = %s\n", user_data);
        // reply to the message
        //nopoll_conn_send_text (conn, "Message received", 16);
  
        return;
}

int main(){

	//创建nopoll的上下文
	noPollCtx      * ctx = NULL;
	ctx = nopoll_ctx_new ();


	/* create options */
	noPollConnOpts * opts;
	opts     = nopoll_conn_opts_new();
	nopoll_conn_opts_set_ssl_protocol (opts, NOPOLL_METHOD_TLSV1_2);

	//监听
	noPollConn *conn = nopoll_conn_tls_new(ctx,opts,"120.77.254.40","12345",NULL,NULL,NULL,NULL);
	if(!nopoll_conn_is_ok(conn)){
		printf("connect error!\n");
		return -1;
	}

	while(1){
		if (nopoll_conn_is_ready (conn))
			break;
		nopoll_sleep (10000);
	}
	// if(!nopoll_conn_wait_until_connection_ready(conn,5)){
	// 	printf("wait error\n");
	// 	return -1;
	// }
	//设置消息处理函数位listerner_on_message
	 nopoll_ctx_set_on_msg(ctx,listener_on_message,NULL);
	if(nopoll_conn_send_text(conn,"Rfish",5) != 5){
		printf("send text error!\n");
	}
	//等待事件通知



	printf("test\n");
	nopoll_loop_wait(ctx,0);
	return 0;

}